/*
 * tick.c
 *
 * realize system tick using Timer0, the period is about 10ms.
 *
 * Copyright (C) 2022 Microwell, Inc.
 * Subject to the GNU Public License, version 2.
 *
 * Author: guoming<guoming@microwell.net>
 */

#include "core.h"
#include "timer.h"

void timer_init(void)
{
#if (TICK_TIMER_ID_0_EN || TICK_TIMER_ID_1_EN)
    uint8_t tmp, timer;
#endif

/***  timer mode and div     ***/
#if (CONFIG_IC_TYPE == CHIP_SS880X)
    tmp = TIMER_TCLKDIV;
    timer = TIMER_MODE;
    /***  timer reload     ***/
    #if (TIMER_MODE == TIMER_8_AUTO_MODE)
        TH0 = (256 - TIMER_VAL) & 0xFF;
    #endif
#elif (TICK_TIMER_ID_0_EN)
    tmp = TIMER0_TCLKDIV;
    timer = CONFIG_TIMER0_MODE;
    /***  timer reload     ***/
    TIMER0_FREQ_SET(CONFIG_TIMER0_FREQ);
#endif

#if (TICK_TIMER_ID_1_EN)
    timer |= (CONFIG_TIMER1_MODE << 4);
    tmp |= (TIMER1_TCLKDIV << 4);
    /***  timer reload     ***/
    TIMER1_FREQ_SET(CONFIG_TIMER1_FREQ);
#endif

#if (TICK_TIMER_ID_0_EN || TICK_TIMER_ID_1_EN)
    MODIFY_REG(TMOD, (M1_CLR_BIT | M1_CLR_BIT), timer);
    MODIFY_REG(TCON1, (TCLKDIV0_CLR | TCLKDIV1_CLR), tmp);
#endif

#if (TICK_TIMER_ID_2_EN)
    /***  timer div     ***/
    MODIFY_REG(T2CON, TCLKDIV2_CLR, (CONFIG_TIMER2_TCLKDIV << 4));
    /***  timer reload     ***/
    TIMER2_FREQ_SET(CONFIG_TIMER2_FREQ);
#endif


/***  timer enable     ***/
#if (TICK_TIMER_ID_SYS_EN)
    STICK_ENABLE();
    #if (TICK_TIMER_ID_SYS_INTERRPUT_EN)
        STICK_INTERRUPT_ENABLE();
    #endif
#endif
#if (TICK_TIMER_ID_0_EN)
    TIMER_0_ENABLE();
    #if (TICK_TIMER_ID_0_INTERRPUT_EN)
        TIMER_0_INTERRUPT_ENABLE();
    #endif
#endif
#if (TICK_TIMER_ID_1_EN)
    TIMER_1_ENABLE();
    #if (TICK_TIMER_ID_1_INTERRPUT_EN)
        TIMER_1_INTERRUPT_ENABLE();
    #endif
#endif
#if (TICK_TIMER_ID_2_EN)
    TIMER_2_ENABLE();
    #if (TICK_TIMER_ID_2_INTERRPUT_EN)
        TIMER_2_INTERRUPT_ENABLE();
    #endif
#endif

}

